<template>
  <div class="cockpit-overview">
    <!-- 顶部时间和刷新 -->
    <div class="cockpit-header">
      <div class="header-left">
        <h2>📊 数据驾驶舱</h2>
        <span class="current-time">{{ currentTime }}</span>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Refresh" @click="handleRefresh" :loading="loading">
          刷新数据
        </el-button>
        <el-switch 
          v-model="autoRefresh" 
          active-text="自动刷新" 
          @change="handleAutoRefreshChange"
        />
      </div>
    </div>

    <!-- 核心指标卡片 -->
    <el-row :gutter="20" class="kpi-cards">
      <el-col :xs="12" :sm="6" v-for="kpi in kpiData" :key="kpi.id">
        <el-card class="kpi-card" :class="kpi.trend">
          <div class="kpi-icon" :style="{ background: kpi.color }">
            <el-icon :size="30">
              <component :is="kpi.icon" />
            </el-icon>
          </div>
          <div class="kpi-content">
            <div class="kpi-title">{{ kpi.title }}</div>
            <div class="kpi-value">{{ kpi.value }}</div>
            <div class="kpi-footer">
              <span :class="'trend-' + kpi.trend">
                <el-icon>
                  <Top v-if="kpi.trend === 'up'" />
                  <Bottom v-else-if="kpi.trend === 'down'" />
                  <Minus v-else />
                </el-icon>
                {{ kpi.change }}
              </span>
              <span class="kpi-compare">较昨日</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要数据图表 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>📈 销售趋势分析</span>
              <el-radio-group v-model="salesPeriod" size="small">
                <el-radio-button label="day">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" id="salesTrendChart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <span>🎯 销售渠道占比</span>
          </template>
          <div class="chart-container" id="channelPieChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 业务数据看板 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <span>📦 库存预警</span>
          </template>
          <div class="warning-list">
            <el-alert
              v-for="item in stockWarnings"
              :key="item.id"
              :title="item.name"
              :type="item.level"
              :closable="false"
              class="warning-item"
            >
              <template #default>
                <div class="warning-content">
                  <span>当前库存: <strong>{{ item.stock }}</strong></span>
                  <span>安全库存: {{ item.minStock }}</span>
                </div>
              </template>
            </el-alert>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <span>💰 收入支出对比</span>
          </template>
          <div class="chart-container" id="incomeExpenseChart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <span>👥 客户分布</span>
          </template>
          <div class="chart-container" id="customerMapChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时动态 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>📋 热销产品排行</span>
          </template>
          <el-table :data="topProducts" stripe>
            <el-table-column type="index" label="排名" width="60" />
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="sales" label="销量" width="100">
              <template #default="{ row }">
                <el-tag type="success">{{ row.sales }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="销售额" width="120">
              <template #default="{ row }">
                <span class="amount-text">¥{{ row.amount.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column label="趋势" width="80">
              <template #default="{ row }">
                <div class="trend-bar">
                  <el-progress 
                    :percentage="row.trend" 
                    :color="getTrendColor(row.trend)"
                    :show-text="false"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>🔔 实时业务动态</span>
          </template>
          <el-timeline class="activity-timeline">
            <el-timeline-item
              v-for="activity in realtimeActivities"
              :key="activity.id"
              :timestamp="activity.time"
              :type="activity.type"
            >
              <div class="activity-content">
                <el-icon :size="16" class="activity-icon">
                  <component :is="activity.icon" />
                </el-icon>
                <span>{{ activity.content }}</span>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 财务概览 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>💵 财务数据概览</span>
              <el-button-group size="small">
                <el-button @click="financePeriod = 'month'">月度</el-button>
                <el-button @click="financePeriod = 'quarter'">季度</el-button>
                <el-button @click="financePeriod = 'year'">年度</el-button>
              </el-button-group>
            </div>
          </template>
          <div class="finance-overview">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="finance-item">
                  <div class="finance-label">总收入</div>
                  <div class="finance-value income">¥1,234,567</div>
                  <div class="finance-change up">+15.3%</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="finance-item">
                  <div class="finance-label">总支出</div>
                  <div class="finance-value expense">¥856,234</div>
                  <div class="finance-change down">-8.2%</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="finance-item">
                  <div class="finance-label">净利润</div>
                  <div class="finance-value profit">¥378,333</div>
                  <div class="finance-change up">+32.5%</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="finance-item">
                  <div class="finance-label">利润率</div>
                  <div class="finance-value rate">30.6%</div>
                  <div class="finance-change up">+2.1%</div>
                </div>
              </el-col>
            </el-row>
            <div class="chart-container" id="financeChart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, Top, Bottom, Minus,
  ShoppingCart, User, Wallet, TrendCharts,
  DocumentChecked, Bell
} from '@element-plus/icons-vue'

// 时间
const currentTime = ref('')
const loading = ref(false)
const autoRefresh = ref(true)
let refreshTimer = null

// 周期选择
const salesPeriod = ref('day')
const financePeriod = ref('month')

// KPI数据
const kpiData = reactive([
  {
    id: 1,
    title: '今日销售额',
    value: '¥128,456',
    change: '+12.5%',
    trend: 'up',
    icon: 'Wallet',
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
  },
  {
    id: 2,
    title: '今日订单数',
    value: '1,256',
    change: '+8.3%',
    trend: 'up',
    icon: 'ShoppingCart',
    color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)'
  },
  {
    id: 3,
    title: '新增客户',
    value: '89',
    change: '-3.2%',
    trend: 'down',
    icon: 'User',
    color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
  },
  {
    id: 4,
    title: '访问量',
    value: '8,456',
    change: '+15.7%',
    trend: 'up',
    icon: 'TrendCharts',
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
  }
])

// 库存预警
const stockWarnings = ref([
  { id: 1, name: 'iPhone 15 Pro', stock: 25, minStock: 50, level: 'error' },
  { id: 2, name: 'MacBook Air M2', stock: 45, minStock: 60, level: 'warning' },
  { id: 3, name: 'AirPods Pro 2', stock: 70, minStock: 80, level: 'warning' }
])

// 热销产品
const topProducts = ref([
  { id: 1, name: 'iPhone 15 Pro Max', sales: 342, amount: 3420000, trend: 95 },
  { id: 2, name: 'MacBook Pro 16', sales: 156, amount: 3120000, trend: 82 },
  { id: 3, name: 'AirPods Pro 2', sales: 567, amount: 1134000, trend: 78 },
  { id: 4, name: 'iPad Air', sales: 234, amount: 1170000, trend: 65 },
  { id: 5, name: 'Apple Watch Ultra', sales: 189, amount: 1323000, trend: 58 }
])

// 实时动态
const realtimeActivities = ref([
  { id: 1, time: '2分钟前', content: '客户张三完成订单支付 ¥12,999', type: 'success', icon: 'ShoppingCart' },
  { id: 2, time: '5分钟前', content: '新增客户：李四', type: 'primary', icon: 'User' },
  { id: 3, time: '8分钟前', content: '库存预警：iPhone 15 Pro库存不足', type: 'warning', icon: 'Bell' },
  { id: 4, time: '10分钟前', content: '订单#2024010812已发货', type: 'info', icon: 'DocumentChecked' },
  { id: 5, time: '15分钟前', content: '客户王五完成订单支付 ¥8,999', type: 'success', icon: 'ShoppingCart' }
])

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 刷新数据
const handleRefresh = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据刷新成功')
  }, 1000)
}

// 自动刷新切换
const handleAutoRefreshChange = (val) => {
  if (val) {
    refreshTimer = setInterval(() => {
      handleRefresh()
    }, 30000) // 30秒刷新一次
    ElMessage.success('已开启自动刷新（30秒）')
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    ElMessage.info('已关闭自动刷新')
  }
}

// 趋势颜色
const getTrendColor = (value) => {
  if (value >= 80) return '#67c23a'
  if (value >= 60) return '#e6a23c'
  return '#f56c6c'
}

// 初始化图表
const initCharts = () => {
  ElMessage.info('图表需要集成ECharts库才能显示')
}

onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  initCharts()
  
  // 默认开启自动刷新
  handleAutoRefreshChange(true)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.cockpit-overview {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.cockpit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.header-left h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.current-time {
  font-size: 14px;
  color: #909399;
}

.header-right {
  display: flex;
  gap: 15px;
  align-items: center;
}

/* KPI卡片 */
.kpi-cards {
  margin-bottom: 20px;
}

.kpi-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s;
}

.kpi-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.kpi-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  padding: 20px;
}

.kpi-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 15px;
}

.kpi-content {
  flex: 1;
}

.kpi-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.kpi-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.kpi-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.trend-flat {
  color: #909399;
}

.kpi-compare {
  color: #909399;
}

/* 图表行 */
.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  border: none;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  background: #fafafa;
  border-radius: 4px;
}

/* 预警列表 */
.warning-list {
  max-height: 300px;
  overflow-y: auto;
}

.warning-item {
  margin-bottom: 10px;
}

.warning-content {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
}

/* 产品排行 */
.amount-text {
  color: #f56c6c;
  font-weight: bold;
}

.trend-bar {
  width: 100%;
}

/* 实时动态 */
.activity-timeline {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.activity-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.activity-icon {
  color: #409eff;
}

/* 财务概览 */
.finance-overview {
  padding: 20px 0;
}

.finance-item {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  background: #fafafa;
}

.finance-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.finance-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.finance-value.income {
  color: #67c23a;
}

.finance-value.expense {
  color: #f56c6c;
}

.finance-value.profit {
  color: #409eff;
}

.finance-value.rate {
  color: #e6a23c;
}

.finance-change {
  font-size: 14px;
}

.finance-change.up {
  color: #67c23a;
}

.finance-change.down {
  color: #f56c6c;
}

/* 响应式 */
@media (max-width: 768px) {
  .cockpit-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .kpi-value {
    font-size: 20px;
  }
  
  .finance-value {
    font-size: 20px;
  }
}
</style>

